package com.sdx.console.crm.thread;

import com.sdx.console.crm.entity.CrmRepresentive;
import com.sdx.console.crm.entity.CrmRepresentiveConfig;
import com.sdx.console.crm.service.CrmRepresentiveConfigService;
import com.sdx.console.crm.service.CrmRepresentiveService;
import org.beetl.sql.core.SQLManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.List;

/**
 * @ClassName CrmStatusScanner
 * @Description: 客服状态扫描线程
 * @author: tanbaocai
 * @date: 2019/7/23 16:34
 */
@Component
public class CrmStatusScanner implements Runnable {
	private static final Logger log = LoggerFactory.getLogger("statuScanner");
	private static final String SQL = "crm.scanner";
	@Resource
	private SQLManager sqlManager;
	@Resource
	private CrmRepresentiveConfigService crmRepresentiveConfigService;


	@Resource
	private CrmRepresentiveService crmRepresentiveService;


	@PostConstruct
	public void init()
	{
		Thread scanThread = new Thread(this);
		scanThread.start();
	}

	@Override
	public void run() {
		log.warn("开始启动客服状态扫描线程");
		while(true) {
			try {
				CrmRepresentiveConfig config = crmRepresentiveConfigService.getConfig();
				int idle = config.getIdleRepresentive();
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.MINUTE,-idle);
				CrmRepresentive param = new CrmRepresentive();
				param.setLastOperTime(calendar.getTime());
				List<CrmRepresentive> representiveList = sqlManager.select(SQL+".selectIdleRepresentive",CrmRepresentive.class,param);
				for (int i = 0; i < representiveList.size(); i++) {
					try {
						CrmRepresentive representive = representiveList.get(i);
						crmRepresentiveService.closeRepresentive(representive);
					}catch (Exception e2) {
						log.error("representive",e2);
					}

				}
			} catch(Exception e) {
				log.error("run",e);
			} finally {
				try {
					Thread.sleep(60000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

}
